package net.dgg.rz.api.production.service;

import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.DggValidateUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.rz.api.production.dao.RecognitionDao;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.ModuleCodeConstant;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.constant.SystemCommonConstant;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.utils.DataPermissionUtils;
import net.dgg.rz.common.utils.InitComponent;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.LevelRuleDao;
import net.dgg.rz.production.dao.PayProductRecordBakDao;
import net.dgg.rz.production.dao.PayProductRecordDao;
import net.dgg.rz.production.dao.ProductOrderDao;
import net.dgg.rz.production.entity.LevelRule;
import net.dgg.rz.production.entity.PayProductRecord;
import net.dgg.rz.production.entity.PayProductRecordBak;
import net.dgg.rz.production.entity.ProductOrder;
import net.dgg.rz.production.entity.dto.UserLevelDto;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.rz.production.utils.OnlyCodeUtils;
import net.dgg.starter.call.GateWayClientUtils;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationDTO;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.role.entity.Role;
import net.dgg.tmd.foundation.platform.role.service.RoleService;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 认款源数据接收service
 * Created by zyou on 2019/3/26.
 */
@Service
public class RecognitionService extends BaseService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private PayProductRecordBakDao payProductRecordBakDao;
    @Autowired
    private PayProductRecordDao payProductRecordDao;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private RecognitionDao recognitionDao;
    @Autowired
    private LevelRuleDao levelRuleDao;
    @Autowired
    private DataPermissionUtils dataPermissionUtils;

    @Value("${salaryUrl}")
    private String salaryUrl;
    /**
     * @Description 接收认款数据
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveRecognitionDatas(Map map) throws ParseException {
        DggValidateUtil.notNull(map, ProductOrderExcption.class,"内容为空");
        DggValidateUtil.notNull(map.get("payRecordJson"), ProductOrderExcption.class,"内容为空");
        List<Map> params = JsonUtil.json2List(map.get("payRecordJson").toString(), Map.class);
        DggValidateUtil.notNull(params, ProductOrderExcption.class,"内容为空");
        for(Map param:params){
            saveRecognitionData(param);
        }
    }

    private void saveRecognitionData(Map params) throws ParseException {
        DggValidateUtil.notNull(params.get("id"), ProductOrderExcption.class,"id为空");
        DggValidateUtil.notNull(params.get("createrId"), ProductOrderExcption.class,"用户id为空");
        DggValidateUtil.notNull(params.get("orderBusinessId"), ProductOrderExcption.class,"销售子订单id为空");
        DggValidateUtil.notNull(params.get("orderBusinessNo"), ProductOrderExcption.class,"销售子订单编号为空");
        DggValidateUtil.notNull(params.get("productId"), ProductOrderExcption.class,"产品id为空");
        DggValidateUtil.notNull(params.get("internalCost"), ProductOrderExcption.class,"内部成本为空");
        DggValidateUtil.notNull(params.get("externalCost"), ProductOrderExcption.class,"外部成本为空");
        DggValidateUtil.notNull(params.get("amount"), ProductOrderExcption.class,"认款金额为空");
        DggValidateUtil.notNull(params.get("amountMonth"), ProductOrderExcption.class,"业绩计算时间为空");
        //通过销售子单id查询是否能够查询到唯一一条数据，如果能查到唯一就处理，未处理数据存储到一个失败记录数据表上
        UserEntity userEntity = userService.findUserById(Long.parseLong(params.get("createrId").toString()));
        DggValidateUtil.notNull(userEntity,ProductOrderExcption.class,"登陆人为空，请重新登陆！");
        //当前登录人部门
        Map curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());

        Long orderBusinessId = Long.parseLong(params.get("orderBusinessId").toString());
        List<ProductOrder> productOrders = productOrderDao.getByOrderBusinessId(orderBusinessId);
        if(productOrders == null || productOrders.size()==0 || productOrders.size()>1){
            PayProductRecordBak payProductRecordBak = new PayProductRecordBak();
            payProductRecordBak.setId(DggKeyWorker.nextId());
            this.saveOpt(payProductRecordBak,userEntity);
            payProductRecordBak.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            payProductRecordBak.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            payProductRecordBak.setDataJson(JSONObject.toJSONString(params));
            payProductRecordBakDao.save(payProductRecordBak);
        }else{
            //内部成本
            BigDecimal nbcb = new BigDecimal(params.get("internalCost").toString());
            //外部成本
            BigDecimal wbcb = new BigDecimal(params.get("externalCost").toString());
            //认款金额
            BigDecimal rkje = new BigDecimal(params.get("amount").toString());

            ProductOrder productOrder = productOrders.get(0);
            if(!ScProductConstant.RZSCORDER_STATUS19.equals(productOrder.getStatus())&&!ScProductConstant.RZSCORDER_STATUS17.equals(productOrder.getStatus())){
                DggValidateUtil.notNull(null, ProductOrderExcption.class,"该订单未完结");
            }

            String prodName = productOrder.getProductName()==null?"":productOrder.getProductName();
            if(prodName.indexOf(SystemCommonConstant.FDFY)==-1){
                //如果签单人是融资流程人员，就是自开发
                Long signUserId = productOrder.getSignUserId();
                int isSelf = 0;
                if(signUserId != null){
                    List<Role> roleList = roleService.findUserRoleDTOByUserId(signUserId);
                    if(roleList != null && roleList.size()>0){
                        for (Role role:roleList) {
                            if("RZSC_FLOW_USER".equals(role.getCode())){
                                isSelf = 1;
                                break;
                            }
                        }
                    }
                }
                BigDecimal zkf = rkje.subtract(nbcb).subtract(wbcb);
                if(signUserId != null && isSelf==1 && zkf.doubleValue()!=0){
                    //自主开发，用自主开发计算方式算计算项
                    Map zzkfMap = new HashMap();
                    zzkfMap.put(ScProductConstant.BUS_YT_DK_NBCB,0);
                    zzkfMap.put(ScProductConstant.BUS_YT_DK_ZKFLR,zkf);
                    zzkfMap.put(ScProductConstant.BUS_YT_DK_FDLR,0);
                    PayProductRecord zzkfPayRecord = compeletPayProductRecord(productOrder,userEntity,curentDept,params);
                    zzkfPayRecord.setPushJson(JSONObject.toJSONString(zzkfMap));
                    zzkfPayRecord.setProductOrderOrgId(productOrder.getSignOrgId());
                    zzkfPayRecord.setProductOrderOrgName(productOrder.getSignOrgName());
                    zzkfPayRecord.setProductOrderUserOrgId(productOrder.getSignUserOrgId());
                    zzkfPayRecord.setProductOrderUserOrgName(productOrder.getSignUserOrgName());
                    zzkfPayRecord.setPayUserId(signUserId);
                    zzkfPayRecord.setPayUserName(productOrder.getSignUserName());
                    //此处做预留
                    zzkfPayRecord.setTeamId(null);
                    zzkfPayRecord.setIsSelf(1);
                    payProductRecordDao.save(zzkfPayRecord);
                }

                if(productOrder.getFlowUserId() != null && nbcb.doubleValue()!=0){
                    //非自主开发
                    Map fzkfMap = new HashMap();
                    fzkfMap.put(ScProductConstant.BUS_YT_DK_NBCB,nbcb);
                    fzkfMap.put(ScProductConstant.BUS_YT_DK_ZKFLR,0);
                    fzkfMap.put(ScProductConstant.BUS_YT_DK_FDLR,0);
                    PayProductRecord fzkfPayRecord = compeletPayProductRecord(productOrder,userEntity,curentDept,params);
                    fzkfPayRecord.setPushJson(JSONObject.toJSONString(fzkfMap));
                    fzkfPayRecord.setProductOrderOrgId(productOrder.getProductOrgId());
                    fzkfPayRecord.setProductOrderOrgName(productOrder.getProductOrgName());
                    fzkfPayRecord.setProductOrderUserOrgId(productOrder.getFlowUserOrgId());
                    fzkfPayRecord.setProductOrderUserOrgName(productOrder.getFlowUserOrgName());
                    fzkfPayRecord.setPayUserId(productOrder.getFlowUserId());
                    fzkfPayRecord.setPayUserName(productOrder.getFlowUserName());
                    //此处做预留
                    fzkfPayRecord.setTeamId(null);
                    fzkfPayRecord.setIsSelf(0);
                    payProductRecordDao.save(fzkfPayRecord);
                }
            }

        }
    }

    /**
     * 设置公共字段
     * @param productOrder
     * @param userEntity
     * @param curentDept
     * @return
     */
    private PayProductRecord compeletPayProductRecord(ProductOrder productOrder,UserEntity userEntity,Map curentDept,Map params) throws ParseException {
        String busitypeCode = params.get("busitypeCode")==null?"":params.get("busitypeCode").toString();//业态code
        String busitypeName = params.get("busitypeName")==null?"":params.get("busitypeName").toString();//业态名称
        String productName = params.get("productName")==null?"":params.get("productName").toString();//产品名称
        String commodityName = params.get("commodityName")==null?"":params.get("commodityName").toString();//商品名称
        Long commodityId = params.get("commodityId")==null?null:Long.parseLong(params.get("commodityId").toString());//商品id
        Long productId = Long.parseLong(params.get("productId").toString());//产品id
        String receiptNo = params.get("receiptNo")==null?"":params.get("receiptNo").toString();//收据编号
        BigDecimal internalCost = new BigDecimal(params.get("internalCost").toString());//内部成本
        BigDecimal externalCost = new BigDecimal(params.get("externalCost").toString());//外部成本
        BigDecimal amount = new BigDecimal(params.get("amount").toString());//认款金额
        Integer type = params.get("type")==null?null:Integer.parseInt(params.get("type").toString());//类型  1 核款 2 退款
        //财务id
        Long paymentId = params.get("paymentId")==null?null:Long.parseLong(params.get("paymentId").toString());
        //认款商品ID（财务系统源数据id
        Long payProductRecordId = Long.parseLong(params.get("id").toString());
        //退款金额
        BigDecimal reimburseAmount = params.get("reimburseAmount")==null?null:new BigDecimal(params.get("reimburseAmount").toString());
        //业绩
        BigDecimal performance = params.get("performance")==null?null:new BigDecimal(params.get("performance").toString());
        //利润
        BigDecimal profit = params.get("profit")==null?null:new BigDecimal(params.get("profit").toString());
        //小业态
        String smallBusiness = params.get("smallBusiness")==null?"":params.get("smallBusiness").toString();
        //小业态名称
        String smallBusinessName = params.get("smallBusinessName")==null?"":params.get("smallBusinessName").toString();
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //业绩计算时间
        Date amountMonth=format.parse(params.get("amountMonth").toString());

        PayProductRecord payProductRecord = new PayProductRecord();
        //获取生产子订单编号
        String rztc = cmsService.getBillNumber(SystemCommonConstant.RZTC);
        ValidateUtils.strNotEmpty(rztc,ProductOrderExcption.class,"融资提成单据号获取失败,请联系管理员！");

        payProductRecord.setId(DggKeyWorker.nextId());
        payProductRecord.setPayNo(rztc);
        this.saveOpt(payProductRecord,userEntity);
        payProductRecord.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        payProductRecord.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        payProductRecord.setBusitypeCode(busitypeCode);
        payProductRecord.setBusitypeName(busitypeName);
        payProductRecord.setProductName(productOrder.getProductName());
        payProductRecord.setCommodityName(productOrder.getGoodsName());
        payProductRecord.setCommodityId(productOrder.getGoodsId());
        payProductRecord.setChannelName(productOrder.getChannelName());
        payProductRecord.setChannelId(productOrder.getChannelId());
        payProductRecord.setProductId(productId);
        payProductRecord.setProductOrderNo(productOrder.getScProductOrderNo());
        payProductRecord.setProductOrderId(productOrder.getId());
        payProductRecord.setOrderBusinessId(productOrder.getOrderBusId());
        payProductRecord.setOrderId(productOrder.getOrderId());
        payProductRecord.setOrderBusinessNo(productOrder.getOrderBusNo());
        payProductRecord.setReceiptNo(receiptNo);
        payProductRecord.setInternalCost(internalCost);
        payProductRecord.setExternalCost(externalCost);
        payProductRecord.setAmount(amount);
        payProductRecord.setType(type);
        payProductRecord.setPaymentId(paymentId);
        payProductRecord.setPayProductRecordId(payProductRecordId);
        payProductRecord.setReimburseAmount(reimburseAmount);
        payProductRecord.setPerformance(performance);
        payProductRecord.setProfit(profit);
        payProductRecord.setSmallBusiness(smallBusiness);
        payProductRecord.setSmallBusinessName(smallBusinessName);
        payProductRecord.setAmountMonth(amountMonth);
        payProductRecord.setIsPush(0);
        payProductRecord.setIsValid(1);
        payProductRecord.setDataJson(JSONObject.toJSONString(params));
        return payProductRecord;
    }

    /**
     * 保存内部下单财务数据
     * @param map
     */
    @Transactional
    public void savePayOrderDatas(Map map) {
        DggValidateUtil.notNull(map, ProductOrderExcption.class,"数据为空");
        DggValidateUtil.notNull(map.get("orderBusinessList"), ProductOrderExcption.class,"数据为空");
        List<Map> mapList = JsonUtil.json2List(map.get("orderBusinessList").toString(),Map.class);
        if(mapList != null && mapList.size()>0){
            for (Map params:mapList) {
                DggValidateUtil.notNull(params.get("id"), ProductOrderExcption.class,"id为空");
                DggValidateUtil.notNull(params.get("orderId"), ProductOrderExcption.class,"销售主单id为空");
                DggValidateUtil.notNull(params.get("no"), ProductOrderExcption.class,"内部订单编号为空");
                DggValidateUtil.notNull(params.get("createrId"), ProductOrderExcption.class,"用户id为空");
                DggValidateUtil.notNull(params.get("payUserId"), ProductOrderExcption.class,"签单人id为空");
                DggValidateUtil.notNull(params.get("amount"), ProductOrderExcption.class,"认款金额为空");
                DggValidateUtil.notNull(params.get("productId"), ProductOrderExcption.class,"产品id为空");
                DggValidateUtil.notNull(params.get("productName"), ProductOrderExcption.class,"产品名称为空");
                DggValidateUtil.notNull(params.get("commodityName"), ProductOrderExcption.class,"商品名称为空");
                DggValidateUtil.notNull(params.get("smallBusiness"), ProductOrderExcption.class,"小业态编号为空");
                BigDecimal amount = new BigDecimal(params.get("amount").toString());
                if(amount.doubleValue()==0 || !SystemCommonConstant.FDFY.equals(params.get("productName").toString())){
                    continue;
                }

                UserEntity userEntity = userService.findUserById(Long.parseLong(params.get("createrId").toString()));
                UserEntity payUserIdEntity = userService.findUserById(Long.parseLong(params.get("payUserId").toString()));
                DggValidateUtil.notNull(userEntity,ProductOrderExcption.class,"登陆人为空，请重新登陆！");
                DggValidateUtil.notNull(payUserIdEntity,ProductOrderExcption.class,"签单人为空");
                //获取生产子订单编号
                String rztc = cmsService.getBillNumber(SystemCommonConstant.RZTC);
                ValidateUtils.strNotEmpty(rztc,ProductOrderExcption.class,"融资提成单据号获取失败,请联系管理员！");
                //当前登录人部门
                Map curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());
                Map payUserIdEntityDept = this.commonMangerExtService.findOrg(payUserIdEntity.getOrgId());
                PayProductRecord payProductRecord = new PayProductRecord();
                payProductRecord.setId(DggKeyWorker.nextId());
                payProductRecord.setDataJson(JSONObject.toJSONString(params));
                payProductRecord.setPayNo(rztc);
                payProductRecord.setProductOrderId(Long.parseLong(params.get("id").toString()));
                payProductRecord.setProductOrderNo(params.get("no").toString());
                payProductRecord.setOrderBusinessNo(rztc);
                payProductRecord.setBusitypeCode(ScProductConstant.BUS_YT_DK);
                payProductRecord.setProductId(Long.parseLong(params.get("productId").toString()));
                payProductRecord.setProductName(params.get("productName").toString());
                payProductRecord.setCommodityName(params.get("commodityName").toString());
                payProductRecord.setSmallBusiness(params.get("smallBusiness").toString());
                payProductRecord.setAmountMonth(new Date());
                payProductRecord.setAmount(new BigDecimal(params.get("amount").toString()));
                payProductRecord.setPayProductRecordId(Long.parseLong(params.get("id").toString()));
                payProductRecord.setOrderId(Long.parseLong(params.get("orderId").toString()));
                payProductRecord.setIsPush(0);
                this.saveOpt(payProductRecord,userEntity);
                payProductRecord.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                payProductRecord.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                payProductRecord.setType(3);
                payProductRecord.setPayUserId(payUserIdEntity.getId());
                payProductRecord.setPayUserName(payUserIdEntity.getRealName()+payUserIdEntity.getLoginName());

                //封装推送薪酬系统数据
                Map fdlrMap = new HashMap();
                fdlrMap.put(ScProductConstant.BUS_YT_DK_NBCB,0);
                fdlrMap.put(ScProductConstant.BUS_YT_DK_ZKFLR,0);
                fdlrMap.put(ScProductConstant.BUS_YT_DK_FDLR,amount);

                payProductRecord.setPushJson(JSONObject.toJSONString(fdlrMap));
                payProductRecord.setIsSelf(0);
                OrganizationDTO sybMap = organizationManager.findOrgParentByLevel(payUserIdEntity.getOrgId(), "ORG_LEVEL_1");
                payProductRecord.setProductOrderOrgId(null == sybMap ? null :sybMap.getId());
                payProductRecord.setProductOrderOrgName(null == sybMap ? null : sybMap.getName());
                payProductRecord.setProductOrderUserOrgId(payUserIdEntity.getOrgId());
                payProductRecord.setProductOrderUserOrgName(null == payUserIdEntityDept ? null : payUserIdEntityDept.get("name").toString());
                payProductRecordDao.save(payProductRecord);
            }
        }else {
            return;
        }


    }

    /**
     * 完结的时候推送认款数据到薪酬系统
     */
    @Transactional(rollbackFor = Exception.class)
    public void pushPayToSalary(Long productOrderId) throws Exception {
        DggValidateUtil.notNull(productOrderId,ProductOrderExcption.class,"生产单id为空");
        Map map = new HashMap();
        map.put("productOrderId",productOrderId);
        map.put("isPush",0);
        map.put("isValid",1);
        List<PayProductRecord> payProductRecords = payProductRecordDao.selectByMap(map);
        if(payProductRecords==null || payProductRecords.size()<=0){
            return;
        }
        List<Map> payParams = new ArrayList<>();
        Map params = null;
        for(PayProductRecord payProductRecord:payProductRecords){
            params = new HashMap();
            params.put("onlyCode", OnlyCodeUtils.getOnlyCode(payProductRecord));
            params.put("source",SystemCommonConstant.ANNEX_FILE_ID_PREFIX);
            params.put("businessNumber",payProductRecord.getOrderBusinessNo());
            params.put("userId",payProductRecord.getPayUserId());
            params.put("businessCode",payProductRecord.getBusitypeCode());
            params.put("defaultLevel",ScProductConstant.DEFAULT_LEVEL);
            params.put("hasMonitor",ScProductConstant.IS_HAS_MONITOR);
            //业绩计算月份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            params.put("synchTime",sdf.format(payProductRecord.getAmountMonth()));
            //事业部id
            params.put("businessUnitId",payProductRecord.getProductOrderOrgId()==null?0L:payProductRecord.getProductOrderOrgId());
            //部门id
            params.put("depId",payProductRecord.getProductOrderUserOrgId()==null?0L:payProductRecord.getProductOrderUserOrgId());
            //属性json  主要包含团队和产品
            Map baseInfo = new HashMap();
            baseInfo.put("teamId",payProductRecord.getTeamId());
            baseInfo.put("productId",payProductRecord.getProductId());
            params.put("baseInfo",baseInfo);
            params.put("dataInfo",JSONObject.parseObject(payProductRecord.getPushJson()));
            payParams.add(params);
        }

        //批量更新推送状态为已推送
        Map pushMap = new HashMap();
        pushMap.put("isPush",1);
        pushMap.put("productOrderId",productOrderId);
        payProductRecordDao.updatePushByProductOrderId(pushMap);
        Map pushParam = new HashedMap();
        pushParam.put("businessDataList", payParams);

        logger.info("businessDataList------>"+JsonUtil.obj2Json(payParams));

        String bas = HttpUtility.postJson(salaryUrl + SystemCommonConstant.PUSH_TO_SALARY,pushParam);
        ResultObj resultObj = JsonUtil.json2Obj(bas, ResultObj.class);
        if (resultObj.getCode() == 0) {
            return;
        }else if(resultObj.getCode() == 1){
            throw new ProductOrderExcption(resultObj.getMsg());
        }else{
            throw new ProductOrderExcption("推送薪酬系统失败");
        }
    }

    /**
     * 查询流程人员列表不分页
     * @param orgId
     * @return
     */
    public List<UserLevelDto> managementList(Map params,Long orgId) {
        DggValidateUtil.notNull(orgId,ProductOrderExcption.class,"部门id为空");
        //查询部门及以下的部门
       /* List<Long> orgIds = new ArrayList<>();
        orgIds = organizationManager.findOrgIdsByPId(orgId);
        orgIds.add(orgId);*/
        dataPermissionUtils.deptRoyaltyDataAccess(params, ModuleCodeConstant.RZSC_ROYALTY_CODE);
        String[] roles = {"RZSC_FLOW_USER"};
        params.put("codes",roles);
        params.put("status",0);
        //params.put("orgIds",orgIds);
        List<UserLevelDto> list = recognitionDao.findUserByRoleCodesAndOrgs(params);
        return list;
    }

    /**
     * 查询流程人员列表分页
     * @param orgId
     * @return
     */
    public List<UserLevelDto> managementListWithPage(Map params,Long orgId) {
        DggValidateUtil.notNull(orgId,ProductOrderExcption.class,"部门id为空");
        //查询部门及以下的部门
        /*List<Long> orgIds = new ArrayList<>();
        orgIds = organizationManager.findOrgIdsByPId(orgId);
        orgIds.add(orgId);*/
        //根据数据权限来
        //数据权限参数注入
        dataPermissionUtils.deptRoyaltyDataAccess(params, ModuleCodeConstant.RZSC_ROYALTY_CODE);
        String[] roles = {"RZSC_FLOW_USER"};
        params.put("codes",roles);
        params.put("status",0);
        //params.put("orgIds",orgIds);
        List<UserLevelDto> list = recognitionDao.findUserByRoleCodesAndOrgsWithPage(params);
        return list;
    }

    /**
     * 查询晋降级规则配置
     * @param params
     * @return
     */
    public List<LevelRule> getLevelRule(Map params) {
        Map map = new HashMap();
        map.put("isValid",1);
        return levelRuleDao.getLevelRule(map);
    }

    /**
     * 查询是否已认款
     * @param params
     */
    public List<Long> queryIsAdmissible(Map params) {
        DggValidateUtil.notNull(params.get("orderId"), ProductOrderExcption.class,"销售单id为空");
        Long orderId = Long.parseLong(params.get("orderId").toString());
        //获取所有并且flag为0的且已完结生产子单销售子单id集合
        List<Long> productOrderBusinessIds = productOrderDao.getByOrderId(orderId);
        return productOrderBusinessIds;
    }
    /**
     * 查询是否已认款,需到订单中心再次查询
     * @param resMap
     * @param params
     */
    public Map queryIsAdmissibleByOrderService(Map resMap,Map params) {
        DggValidateUtil.notNull(params.get("orderId"), ProductOrderExcption.class,"销售单id为空");
        Map param = new HashMap();
        param.put("orderId",params.get("orderId"));
        Object resultStr = GateWayClientUtils.doGet(InitComponent.qdsApiUrl+"/api/white/order/v1/select_order_detail.do", param);
        DggValidateUtil.notNull(resultStr, ProductOrderExcption.class,"请求订单中接口异常！");
        JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(resultStr));
        if (result.getString("code") == "200") {
            JSONObject jsonObject = result.getJSONObject("data");
            if(null == jsonObject || "QDS_SOURCE_IBOSS".equals(jsonObject.getString("orderSourceCode"))){
                resMap.put("isCrm4","yes");
            }else{
                resMap.put("isCrm4","no");
                resMap.put("data",new ArrayList<Long>());
            }
        }else{
            logger.info("查询失败！");
            resMap.put("isCrm4","no");
            resMap.put("data",new ArrayList<Long>());
        }
        return resMap;
    }
    /**
     * 首先查询是否是crm4.0老数据，如果是（没有查到生产单，就返回是老数据，告诉财务可以认款）
     * @param params
     * @return
     */
    public int countOrderByOrderId(Map params) {
        DggValidateUtil.notNull(params.get("orderId"), ProductOrderExcption.class,"销售单id为空");
        Long orderId = Long.parseLong(params.get("orderId").toString());
        int countOrderByOrderId = productOrderDao.countOrderByOrderId(orderId);
        return countOrderByOrderId;
    }
}
